package cn.bearspark.framework.web.starter.vo;

import cn.bearspark.common.dto.ResponseDTO;
import cn.bearspark.common.enumeration.RespCodeEnum;
import lombok.Data;

/**
 * 响应的视图对象
 *
 * @param <T> 响应数据的类型
 * @author f
 */
@Data
public class ResponseVO<T> {

    /**
     * 响应码
     *
     * @see RespCodeEnum
     */
    private Integer code;

    /**
     * 异常响应的描述
     */
    private String msg;

    /**
     * 成功响应返回的数据
     */
    private T data;

    /**
     * 构建一个糟糕请求的响应
     *
     * @param msg 糟糕请求的原因
     * @return 糟糕请求响应
     */
    public static <T> ResponseVO<T> badRequest(String msg) {
        ResponseVO<T> badRequest = new ResponseVO<>();
        badRequest.setCode(RespCodeEnum.BAD_REQUEST.getCode());
        badRequest.setMsg(msg);
        return badRequest;
    }

    /**
     * 构建一个失败的响应
     *
     * @param msg 失败原因
     * @return 失败响应
     */
    public static <T> ResponseVO<T> fail(String msg) {
        ResponseVO<T> fail = fail();
        fail.setMsg(msg);
        return fail;
    }

    /**
     * 构建一个失败的响应
     *
     * @return 失败响应
     */
    public static <T> ResponseVO<T> fail() {
        ResponseVO<T> fail = new ResponseVO<>();
        fail.setCode(RespCodeEnum.SERVER_ERROR.getCode());
        return fail;
    }

    /**
     * 构建一个（不带数据的）成功响应
     *
     * @return 成功响应
     */
    public static <T> ResponseVO<T> success() {
        ResponseVO<T> success = new ResponseVO<>();
        success.code = RespCodeEnum.OK.getCode();
        return success;
    }

    /**
     * 构建一个成功的响应
     *
     * @param data 成功的数据
     * @return 成功响应
     */
    public static <T> ResponseVO<T> success(T data) {
        ResponseVO<T> success = new ResponseVO<>();
        success.code = RespCodeEnum.OK.getCode();
        success.data = data;
        return success;
    }

    /**
     * 获取一个响应视图对象，该对象的 data 字段为 null
     *
     * @param resp 响应
     * @return 响应的视图对象
     */
    public static ResponseVO<Object> response(ResponseDTO<?> resp) {
        int code = resp.getCode();
        ResponseVO<Object> responseVO = new ResponseVO<>();
        responseVO.setCode(code);
        if (code != RespCodeEnum.OK.getCode()) {
            // 失败的响应需要填写原因
            responseVO.setMsg(resp.getMsg());
        }
        return responseVO;
    }
}
